import type { App } from 'vue'
import { createI18n } from 'vue-i18n'

import { useLocaleStoreWithOut } from '@/store/locale'

import { localeMap } from './config'
import { setHtmlPageLang, setLoadLocalePool } from './helper'

async function createI18nOptions() {
  const localeStore = useLocaleStoreWithOut()
  const locale = localeStore.getLocale
  const defaultLocal = await import(`./lang/${locale}.ts`)
  const message = defaultLocal.default?.message ?? {}

  setHtmlPageLang(locale)
  setLoadLocalePool((loadLocalePool) => {
    loadLocalePool.push(locale)
  })

  console.log('message', message)

  return {
    locale,
    // legacy: false,
    fallbackLocale: localeMap.zh_CN, // set fallback locale
    messages: {
      [locale]: message as { [key: string]: string },
    },
    globalInjection: true,
    silentTranslationWarn: true, // true - warning off
    missingWarn: false,
    silentFallbackWarn: true,
  }
}

// const options = await createI18nOptions()
// export const i18n = createI18n(options)

// setup i18n instance with global
export async function setupI18n(app: App) {
  const options = await createI18nOptions()
  const i18n = createI18n(options)
  // 解决vite打包不能使用top-level-await,所以把它挂载到window上方便使用
  ;(window as any).i18n = i18n
  app.use(i18n)
}
